package com.gome.ocean.service.utils;

import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.service.utils.job.CreateJobUtils;


/**
 * Created by liuqingxia on 2016/2/18.
 */
public class DataXCommonUtils {

    public static String[] keysAgainstQuerySql = new String[] { "columns", "table" };

    public static boolean keyCanBeNull(String key, String[] canBeNullKeyArr, HttpServletRequest req) {

        List<String> canBeNullKeys = Arrays.asList(canBeNullKeyArr);
        List<String> keyListAgainstQuerySql = Arrays.asList(keysAgainstQuerySql);
        String querySqlParamValue = getQuerySqlParamValue(req);

        if (keyListAgainstQuerySql.contains(key) && StringUtils.isNotBlank(querySqlParamValue)) {
            return true;
        }
        if ("querySql".equals(key) && !keysAgainstQuerySqlHaveNullValue(req)) {
            return true;
        }
        if (canBeNullKeys.contains(key)) {
            return true;
        }
        return false;
    }

    public static String getQuerySqlParamValue(HttpServletRequest req) {
        String querySqlParamName = CreateJobUtils.addPrefix(Constants.REQUEST_READER_PARAM_PRE, "querySql");
        return req.getParameter(querySqlParamName);
    }

    public static boolean keysAgainstQuerySqlHaveNullValue(HttpServletRequest req) {
        for (String keyAgainstQuerySql : keysAgainstQuerySql) {
            String paramName = CreateJobUtils.addPrefix(Constants.REQUEST_READER_PARAM_PRE, keyAgainstQuerySql);
            String paramValue = req.getParameter(paramName);
            if (StringUtils.isBlank(paramValue)) {
                return true;
            }
        }
        return false;
    }
}
